<?php

declare(strict_types=1);

namespace app\shop\controller\api\user;

use think\Request;
use app\shop\controller\api\ShopBase;
use sheep\exception\SheepException;
use app\shop\model\user\Invoice as UserInvoiceModel;
use think\facade\Db;

class Invoice extends ShopBase
{

    public function list(Request $request)
    {
        $user = $this->auth()->user();

        $userInvoices = UserInvoiceModel::where('user_id', $user->id)
            ->order('id', 'asc')
            ->select();

        return success('获取成功', $userInvoices);
    }


    /**
     * 添加发票抬头
     *
     * @return \think\Response
     */
    public function add(Request $request)
    {
        $user = $this->auth()->user();

        $params = $request->only([
            'type', 'name', 'tax_no', 'address', 'mobile', 'bank_name', 'bank_no'
        ]);
        $params['user_id'] = $user->id;
        $this->svalidate($params, ".add");

        Db::transaction(function () use ($user, $params) {
            $userInvoice = new UserInvoiceModel();
            $userInvoice->save($params);
        });

        return success('保存成功');
    }



    /**
     * 发票详情
     *
     * @param  $id
     * @return \think\Response
     */
    public function detail($id)
    {
        $user = $this->auth()->user();
        $userInvoice = UserInvoiceModel::where('user_id', $user->id)->findOrFail($id);

        return success('获取成功', $userInvoice);
    }



    /**
     * 编辑发票
     *
     * @return \think\Response
     */
    public function edit(Request $request, $id)
    {
        $user = $this->auth()->user();

        $params = $request->only([
            'type', 'name', 'tax_no', 'address', 'mobile', 'bank_name', 'bank_no'
        ]);
        $this->svalidate($params, ".edit");

        $userInvoice = UserInvoiceModel::where('user_id', $user->id)->findOrFail($id);
        Db::transaction(function () use ($params, $userInvoice) {
            $userInvoice->save($params);
        });

        return success('保存成功');
    }


    /**
     * 删除发票
     *
     * @param string $id 要删除的发票
     * @return void
     */
    public function delete($id)
    {
        $user = $this->auth()->user();

        $userInvoice = UserInvoiceModel::where('user_id', $user->id)->findOrFail($id);
        $userInvoice->delete();

        return success('删除成功');
    }
}
